package com.zjj.learn.designmodel.pattern.factory.config_factory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/** 生产咖啡的工厂
 * 采用配置文件的方式获取对象
 * *** @author zjj_admin
 * *** 2022/4/7 9:28
 */
public class CoffeeFactory {

    //加载配置文件，获取配置文件中的全类名，并创建该类的对象进行存储
    //1、定义一个容器用于存储咖啡对象

    private static Map<String,Coffee> map = new HashMap<>();

    //2、加载配置文件，只需要加载一次
    static {

        //创建Properties对象
        Properties properties = new Properties();
        //加载配置文件
        InputStream inputStream = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");

/*
        String filePath = "C:\\Users\\zjj_admin\\Desktop\\test_factory.txt";

        File file = new File(filePath);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
*/

/*        FileOutputStream out = null;
       try {
            FileInputStream is = new FileInputStream(filePath);
            out = new FileOutputStream(filePath);

            byte[] buffer = new byte[1024];
            int len ;
            while ((len = inputStream.read(buffer))>0){
                System.out.println("len = " + len);
                System.out.println("..."+new String(buffer,0,len));
                out.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           try {
               out.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }*/

        try {
            properties.load(inputStream);
            Set<Object> keys = properties.keySet();

            for (Object key : keys) {
               // System.out.println("key = " + key);
                String className = properties.getProperty((String) key);
               // System.out.println("className = " + className);
                //通过反射获取类对象
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                map.put((String) key,coffee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //根据名称获取类的对象
    public static Coffee createCoffee(String className){
        return map.get(className);
    }
}
